<template>
  <view class="order-list-page">
    <!-- 订单状态标签 -->
    <view class="status-tabs">
      <view 
        v-for="tab in statusTabs" 
        :key="tab.value"
        class="tab-item"
        :class="{ active: selectedStatus === tab.value }"
        @click="selectStatus(tab.value)"
      >
        {{ tab.label }}
      </view>
    </view>

    <!-- 订单列表 -->
    <view class="order-list" v-if="orderList.length > 0">
      <view 
        v-for="order in orderList" 
        :key="order.id"
        class="order-item"
        @click="goToOrderDetail(order.id)"
      >
        <!-- 订单头部 -->
        <view class="order-header">
          <view class="merchant-info">
            <text class="merchant-name">{{ order.merchantName }}</text>
            <text class="order-time">{{ formatTime(order.createTime) }}</text>
          </view>
          <text class="order-status" :class="getStatusClass(order.status)">
            {{ getStatusText(order.status) }}
          </text>
        </view>

        <!-- 课程信息 -->
        <view class="course-info">
          <image :src="order.courseInfo.coverUrl" class="course-image" mode="aspectFill" />
          <view class="course-details">
            <text class="course-title">{{ order.courseInfo.title }}</text>
            <text class="course-desc">{{ order.courseInfo.description }}</text>
            <view class="course-meta">
              <text class="course-price">¥{{ order.courseInfo.price }}</text>
              <text class="course-quantity">x{{ order.quantity }}</text>
            </view>
          </view>
        </view>

        <!-- 订单金额 -->
        <view class="order-amount">
          <text class="amount-label">实付金额：</text>
          <text class="amount-value">¥{{ order.totalAmount }}</text>
        </view>

        <!-- 操作按钮 -->
        <view class="order-actions">
          <button 
            v-if="order.status === 'pending'"
            class="action-btn cancel-btn"
            @click.stop="cancelOrder(order)"
          >
            取消订单
          </button>
          <button 
            v-if="order.status === 'pending'"
            class="action-btn pay-btn"
            @click.stop="payOrder(order)"
          >
            立即支付
          </button>
          <button 
            v-if="order.status === 'confirmed'"
            class="action-btn confirm-btn"
            @click.stop="confirmOrder(order)"
          >
            确认收货
          </button>
          <button 
            v-if="order.status === 'completed'"
            class="action-btn review-btn"
            @click.stop="reviewOrder(order)"
          >
            评价
          </button>
          <button 
            v-if="canRefund(order.status)"
            class="action-btn refund-btn"
            @click.stop="refundOrder(order)"
          >
            申请退款
          </button>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else-if="!loading">
      <image src="../../static/images/empty-order.png" class="empty-image" />
      <text class="empty-text">暂无相关订单</text>
      <button class="go-shopping-btn" @click="goShopping">去逛逛</button>
    </view>

    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore && orderList.length > 0">
      <button class="load-more-btn" @click="loadMore" :loading="loadingMore">
        {{ loadingMore ? '加载中...' : '加载更多' }}
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Taro, { useRouter, useReachBottom } from '@tarojs/taro'
import orderApi from '@/api/order'
import { formatTime, showLoading, hideLoading, showError, navigateTo } from '@/utils'

// 路由参数
const router = useRouter()
const { status } = router.params

// 响应式数据
const loading = ref(false)
const loadingMore = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = ref(10)

const selectedStatus = ref(status || 'all')
const orderList = ref([])

// 状态标签
const statusTabs = ref([
  { label: '全部', value: 'all' },
  { label: '待付款', value: 'pending' },
  { label: '待确认', value: 'paid' },
  { label: '已确认', value: 'confirmed' },
  { label: '已完成', value: 'completed' }
])

// 页面加载
onMounted(() => {
  loadOrderList()
})

// 加载订单列表
const loadOrderList = async (isLoadMore = false) => {
  try {
    if (!isLoadMore) {
      loading.value = true
      currentPage.value = 1
      orderList.value = []
    } else {
      loadingMore.value = true
    }

    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      status: selectedStatus.value === 'all' ? '' : selectedStatus.value
    }

    const result = await orderApi.getOrderList(params)
    
    if (result.code === 200) {
      const newList = result.data.list || []
      
      if (isLoadMore) {
        orderList.value = [...orderList.value, ...newList]
      } else {
        orderList.value = newList
      }
      
      hasMore.value = newList.length === pageSize.value
      currentPage.value++
    }
  } catch (error) {
    console.error('加载订单列表失败:', error)
    showError('加载失败，请重试')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 选择状态
const selectStatus = (status) => {
  selectedStatus.value = status
  loadOrderList()
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待付款',
    paid: '待确认',
    confirmed: '已确认',
    completed: '已完成',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态样式类
const getStatusClass = (status) => {
  return `status-${status}`
}

// 判断是否可以退款
const canRefund = (status) => {
  return ['paid', 'confirmed'].includes(status)
}

// 取消订单
const cancelOrder = async (order) => {
  try {
    const res = await Taro.showModal({
      title: '确认取消',
      content: '确定要取消这个订单吗？'
    })
    
    if (res.confirm) {
      showLoading('取消中...')
      await orderApi.cancelOrder(order.id, '用户主动取消')
      
      Taro.showToast({
        title: '订单已取消',
        icon: 'success'
      })
      
      // 刷新列表
      loadOrderList()
    }
  } catch (error) {
    console.error('取消订单失败:', error)
    showError('取消失败，请重试')
  } finally {
    hideLoading()
  }
}

// 支付订单
const payOrder = async (order) => {
  try {
    showLoading('发起支付...')
    
    const result = await orderApi.wxPay(order.id)
    
    if (result.code === 200) {
      const paymentData = result.data
      
      // 调用微信支付
      await Taro.requestPayment({
        timeStamp: paymentData.timeStamp,
        nonceStr: paymentData.nonceStr,
        package: paymentData.package,
        signType: paymentData.signType,
        paySign: paymentData.paySign
      })
      
      Taro.showToast({
        title: '支付成功',
        icon: 'success'
      })
      
      // 刷新列表
      loadOrderList()
    }
  } catch (error) {
    console.error('支付失败:', error)
    if (error.errMsg && error.errMsg.includes('cancel')) {
      Taro.showToast({
        title: '支付已取消',
        icon: 'none'
      })
    } else {
      showError('支付失败，请重试')
    }
  } finally {
    hideLoading()
  }
}

// 确认收货
const confirmOrder = async (order) => {
  try {
    const res = await Taro.showModal({
      title: '确认收货',
      content: '确定已收到课程服务吗？'
    })
    
    if (res.confirm) {
      showLoading('确认中...')
      await orderApi.confirmOrder(order.id)
      
      Taro.showToast({
        title: '确认成功',
        icon: 'success'
      })
      
      // 刷新列表
      loadOrderList()
    }
  } catch (error) {
    console.error('确认收货失败:', error)
    showError('确认失败，请重试')
  } finally {
    hideLoading()
  }
}

// 评价订单
const reviewOrder = (order) => {
  navigateTo('/pages/order/review', { orderId: order.id })
}

// 申请退款
const refundOrder = (order) => {
  navigateTo('/pages/order/refund', { orderId: order.id })
}

// 跳转订单详情
const goToOrderDetail = (orderId) => {
  navigateTo('/pages/order/detail', { id: orderId })
}

// 去购物
const goShopping = () => {
  Taro.switchTab({
    url: '/pages/index/index'
  })
}

// 加载更多
const loadMore = () => {
  if (!loadingMore.value && hasMore.value) {
    loadOrderList(true)
  }
}

// 触底加载更多
useReachBottom(() => {
  loadMore()
})
</script>

<style lang="less">
.order-list-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.status-tabs {
  display: flex;
  background: white;
  border-bottom: 1px solid #f0f0f0;

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 32px 16px;
    font-size: 28px;
    color: #666;
    border-bottom: 4px solid transparent;

    &.active {
      color: #3478F6;
      border-bottom-color: #3478F6;
    }
  }
}

.order-list {
  padding: 24px 32px;

  .order-item {
    background: white;
    border-radius: 16px;
    padding: 32px 24px;
    margin-bottom: 24px;

    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 24px;

      .merchant-info {
        .merchant-name {
          font-size: 28px;
          font-weight: 600;
          color: #333;
          display: block;
          margin-bottom: 8px;
        }

        .order-time {
          font-size: 24px;
          color: #999;
          display: block;
        }
      }

      .order-status {
        font-size: 28px;
        font-weight: 500;

        &.status-pending {
          color: #F5A623;
        }

        &.status-paid {
          color: #3478F6;
        }

        &.status-confirmed {
          color: #52C41A;
        }

        &.status-completed {
          color: #52C41A;
        }

        &.status-cancelled {
          color: #999;
        }

        &.status-refunded {
          color: #FF4D4F;
        }
      }
    }

    .course-info {
      display: flex;
      margin-bottom: 24px;

      .course-image {
        width: 160px;
        height: 120px;
        border-radius: 12px;
        flex-shrink: 0;
      }

      .course-details {
        flex: 1;
        margin-left: 24px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .course-title {
          font-size: 28px;
          font-weight: 500;
          color: #333;
          margin-bottom: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .course-desc {
          font-size: 24px;
          color: #666;
          line-height: 1.4;
          margin-bottom: 16px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }

        .course-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .course-price {
            font-size: 32px;
            font-weight: 600;
            color: #F5A623;
          }

          .course-quantity {
            font-size: 24px;
            color: #999;
          }
        }
      }
    }

    .order-amount {
      text-align: right;
      margin-bottom: 24px;

      .amount-label {
        font-size: 28px;
        color: #666;
      }

      .amount-value {
        font-size: 32px;
        font-weight: 600;
        color: #F5A623;
      }
    }

    .order-actions {
      display: flex;
      justify-content: flex-end;
      gap: 16px;

      .action-btn {
        border: 1px solid #e0e0e0;
        border-radius: 24px;
        padding: 16px 32px;
        font-size: 28px;
        background: white;

        &.cancel-btn {
          color: #666;
        }

        &.pay-btn {
          background: #3478F6;
          color: white;
          border-color: #3478F6;
        }

        &.confirm-btn {
          background: #52C41A;
          color: white;
          border-color: #52C41A;
        }

        &.review-btn {
          color: #3478F6;
          border-color: #3478F6;
        }

        &.refund-btn {
          color: #FF4D4F;
          border-color: #FF4D4F;
        }
      }
    }
  }
}

.empty-state {
  text-align: center;
  padding: 120px 40px;

  .empty-image {
    width: 200px;
    height: 200px;
    margin-bottom: 32px;
  }

  .empty-text {
    font-size: 28px;
    color: #999;
    display: block;
    margin-bottom: 32px;
  }

  .go-shopping-btn {
    background: #3478F6;
    color: white;
    border: none;
    border-radius: 24px;
    padding: 16px 32px;
    font-size: 28px;
  }
}

.load-more {
  padding: 32px;
  text-align: center;

  .load-more-btn {
    background: #f8f9fa;
    color: #666;
    border: none;
    border-radius: 24px;
    padding: 16px 48px;
    font-size: 28px;
  }
}
</style>